/*
 * @Author: xiaosihan 
 * @Date: 2021-12-22 20:52:12 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2022-02-15 16:16:10
 */

import Transition from "three-base/Transition";
import { Sprite, TextureLoader, Vector3, Vector2, BufferGeometry, Camera, Group, Material, Scene, WebGLRenderer, Matrix4 } from "three";



/**
 * 精灵模型
 */
export default class MenuSprite extends Sprite {

    constructor(url: string) {
        super();
        this.scale.set(100, 100, 100);
        this.setMap(url);
        this.transition.setBezier([0.5, 0.5, 0.5, 0.5]);
        this.transition.setDuration(500);

        this.material.alphaTest = 0.1;
        this.geometry.computeBoundingBox();
    }

    static tempVector = new Vector3();

    startPosition = new Vector3(0, 100, 0);

    endPosition = new Vector3(0, 0, 0);

    transition = (() => {
        const transition = new Transition({ x: 0, y: 100, z: 0 });

        transition.onChange(({ x, y, z }) => {
            this.position.set(x, y, z);
        });

        return transition;
    })();

    // 此元素在屏幕空间中的位置
    vector2 = new Vector2();

    vector2NeedUpdata = true;

    cursor?: string = undefined; // 鼠标样式

    onClick?: () => void;

    setMap(url: string) {
        this.material.map = new TextureLoader().load(url);
    }

    // 展开特效
    open() {
        this.transition.set({
            x: this.endPosition.x,
            y: this.endPosition.y,
            z: this.endPosition.z
        });
    }

    // 收起特效
    close() {
        this.transition.set({
            x: this.startPosition.x,
            y: this.startPosition.y,
            z: this.startPosition.z
        });
    }

    onBeforeRender = (renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, material: Material, group: Group) => {

        if (this.vector2NeedUpdata) {
            this.vector2NeedUpdata = false;

            const size = renderer.getSize(new Vector2);

            const widthHalf = size.x / 2;
            const heightHalf = size.y / 2;

            this.getWorldPosition(MenuSprite.tempVector);

            var p = MenuSprite.tempVector.project(camera);
            const x = p.x * widthHalf + widthHalf;
            const y = -p.y * heightHalf + heightHalf;
            this.vector2.set(x, y);
        }
    }

}